package com.czk.gulimall.ware.config;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/4/17 14:43
 */
@Configuration
@Slf4j
public class MyRabbitConfig {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @RabbitListener(queues = "stock.release.stock.queue")
    public void listen( Channel channel, Message message) throws IOException {
        log.info("收到订单过期订单，订单id{}","xx");
        // 手动确认收到消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
    @Bean
    public MessageConverter messageConverter() {
        // 使用json序列化消息
        return new Jackson2JsonMessageConverter();
    }



    @Bean
    public Exchange orderEventExchange() {
        TopicExchange topicExchange = new TopicExchange("stock-event-exchange", true, false, null);
        return topicExchange;
    }

    @Bean
    public Queue orderDelayQueue() {

        // 设置特殊属性
        Map<String, Object> map = new HashMap<>();
        // 设置死信队列的交换机
        map.put("x-dead-letter-exchange", "stock-event-exchange");
        // 陆游键
        map.put("x-dead-letter-routing-key", "stock.release.stock");
        // 过期时间
        map.put("x-message-ttl", 120000);
        Queue queue = new Queue("stock.delay.queue", true, false, false,map);
        return queue;
    }

    @Bean
    public Queue orderReleaseOrderQueue() {
        Queue queue = new Queue("stock.release.stock.queue", true, false, false, null);
        return queue;
    }

    @Bean
    public Binding orderCreateOrderBingding() {
        Binding binding = new Binding("stock.delay.queue", Binding.DestinationType.QUEUE, "stock-event-exchange", "stock.locked", null);
        return binding;
    }

    @Bean
    public Binding orderReleaseOrderBingding() {
        Binding binding = new Binding("stock.release.stock.queue", Binding.DestinationType.QUEUE, "stock-event-exchange", "stock.release.#", null);
        return binding;
    }
}
